# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2021/10/24 16:44
# @File           : views.py
# @IDE            : PyCharm
# @desc           : 主要接口文件

import time
from typing import Optional, List
from fastapi import APIRouter, Depends, Query
from utils.response import SuccessResponse
from . import schemas, crud
from sqlalchemy.ext.asyncio import AsyncSession
from core.database import main_db_getter

app = APIRouter()


@app.get("/test/", summary="测试接口状态")
def app_root():
    data = {
        "当前时间": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        "test": "主管理系统用户管理",
        "status": "success"
    }
    return SuccessResponse(data=data)


@app.post("/users/", summary="创建用户信息", response_model=schemas.VadminAuthUserOut)
async def create_user(user: schemas.VadminAuthUserIn, db: AsyncSession = Depends(main_db_getter)):
    return SuccessResponse(await crud.VadminAuthUserDal(db).create_data(data=user))


@app.get("/users/", summary="获取用户列表")
async def get_users(page: int = 1, page_size: int = 10, db: AsyncSession = Depends(main_db_getter),
                    name: Optional[str] = Query(None, title="姓名", description="查询姓名"),
                    telephone: Optional[int] = Query(None, title="手机号", description="查询手机号")):
    datas = await crud.VadminAuthUserDal(db).get_datas(page, page_size, name=name, telephone=telephone)
    count = await crud.VadminAuthUserDal(db).get_count(name=name, telephone=telephone)
    return SuccessResponse(datas, count=count)


@app.delete("/users/", summary="批量删除用户")
async def delete_users(ids: List[int], db: AsyncSession = Depends(main_db_getter)):
    await crud.VadminAuthUserDal(db).delete_datas(ids=ids)
    return SuccessResponse("删除成功")


@app.put("/users/{id}/", summary="更新用户信息", response_model=schemas.VadminAuthUserOut)
async def put_users(data_id: int, data: schemas.VadminAuthUserUpdate, db: AsyncSession = Depends(main_db_getter)):
    return SuccessResponse(await crud.VadminAuthUserDal(db).put_data(data_id, data))
